package org.dfzt.modules.message.job;
import java.util.List;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.dfzt.common.util.DateUtils;
import org.dfzt.common.util.SpringContextUtils;
import org.dfzt.modules.message.entity.SysMessage;
import org.dfzt.modules.message.handle.ISendMsgHandle;
import org.dfzt.modules.message.handle.enums.SendMsgStatusEnum;
import org.dfzt.modules.message.handle.enums.SendMsgTypeEnum;
import org.dfzt.modules.message.service.ISysMessageService;
import org.dfzt.modules.message.service.impl.SysMessageServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 发送消息任务
 */
public class SendMsgJob implements SimpleJob {
	private static final Log log = LogFactory.getLog(SendMsgJob.class);

	private static ISysMessageService sysMessageService;

	@Override
	public void execute(ShardingContext shardingContext) {
		log.info(String.format(" dfzt-parent 发送消息任务 SendMsgJob !  时间:" + DateUtils.getTimestamp()));
		// 1.读取消息中心数据，只查询未发送的和发送失败不超过次数的
		QueryWrapper<SysMessage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("es_send_status", SendMsgStatusEnum.WAIT.getCode())
				.or(i -> i.eq("es_send_status", SendMsgStatusEnum.FAIL.getCode()).lt("es_send_num", 6));
		if (sysMessageService == null) {
			sysMessageService = SpringContextUtils.getBean(SysMessageServiceImpl.class);
		}
		List<SysMessage> sysMessages = sysMessageService.list(queryWrapper);
		if (sysMessages != null && sysMessages.size()>0){
			log.info(sysMessages.toString());
			// 2.根据不同的类型走不通的发送实现类
			for (SysMessage sysMessage : sysMessages) {
				ISendMsgHandle sendMsgHandle = null;
				try {
					if (sysMessage.getEsType().equals(SendMsgTypeEnum.EMAIL.getType())) {
						sendMsgHandle = (ISendMsgHandle) Class.forName(SendMsgTypeEnum.EMAIL.getImplClass()).newInstance();
					} else if (sysMessage.getEsType().equals(SendMsgTypeEnum.SMS.getType())) {
						sendMsgHandle = (ISendMsgHandle) Class.forName(SendMsgTypeEnum.SMS.getImplClass()).newInstance();
					} else if (sysMessage.getEsType().equals(SendMsgTypeEnum.WX.getType())) {
						sendMsgHandle = (ISendMsgHandle) Class.forName(SendMsgTypeEnum.WX.getImplClass()).newInstance();
					}
				} catch (Exception e) {
					log.error(e.getMessage(),e);
				}
				Integer sendNum = sysMessage.getEsSendNum();
				try {
					sendMsgHandle.SendMsg(sysMessage.getEsReceiver(), sysMessage.getEsTitle(),
							sysMessage.getEsContent().toString());
					// 发送消息成功
					sysMessage.setEsSendStatus(SendMsgStatusEnum.SUCCESS.getCode());
				} catch (Exception e) {
					// 发送消息出现异常
					sysMessage.setEsSendStatus(SendMsgStatusEnum.FAIL.getCode());
				}
				sysMessage.setEsSendNum(++sendNum);
				// 发送结果回写到数据库
				sysMessageService.updateById(sysMessage);
			}
		} else {
			log.info("未查询到可发送的消息");
		}
	}
}
